import re
import os


# 定义编程语言列表
LANGUAGE_KEYWORDS = {
    "javascript": ["JavaScript", "var ", "let "],
    "python": ["Python", "def ", "import "],
    "java": ["Java", "class ", "public static void main"],
    "c": ["C", "#include", "int main"],
    "c++": ["C++", "class ", "include"],
    "ruby": ["Ruby", "def ", "puts"],
    "go": ["Go", "package ", "func "],
    "rust": ["Rust", "fn ", "use "],
    "swift": ["Swift", "func ", "import "],
    "kotlin": ["Kotlin", "fun ", "import "]
}


def convert_table_to_codeblock(md_text):
    # 匹配表格内容，并将 <br> 替换为换行符
    def replace_br(match):
        content = match.group(1)
        content = re.sub(r'<br\s*/?>', '\n', content)  # 将 <br> 转换为换行符
        language = detect_language(content)
        if language:
            # 去除语言关键字
            for lang_keyword in LANGUAGE_KEYWORDS[language]:
                content = content.replace(lang_keyword, "").strip()
        return f'```{language}\n{content}\n```'

    # 处理 <td> 内容，并替换为代码块
    md_text = re.sub(r'<table[^>]*>.*?<td>(.*?)<\/td>.*?<\/table>', replace_br, md_text, flags=re.DOTALL)
    return md_text


def convert_img_to_markdown(md_text):
    # 将 <img> 标签转换为 Markdown 格式
    md_text = re.sub(r'<img src="(.*?)" id=".*?"\/?>', r'![Image](\1)', md_text)
    return md_text


def detect_language(content):
    # 语言关键词字典，键为语言标记，值为该语言的关键词列表
    for lang, keywords in LANGUAGE_KEYWORDS.items():
        for keyword in keywords:
            if keyword in content:
                return lang
    return ""


def convert_docx_md(md_text):
    # 进行表格和图片的综合处理
    md_text = convert_table_to_codeblock(md_text)
    md_text = convert_img_to_markdown(md_text)
    return md_text


def process_markdown_file(input_md_path):
    # 读取 Markdown 文件
    with open(input_md_path, 'r', encoding='utf-8') as file:
        md_text = file.read()

    # 二次转换
    converted_md_text = convert_docx_md(md_text)

    # 生成输出文件路径
    base_name = os.path.basename(input_md_path)
    output_md_path = os.path.join(os.getcwd(), f"converted_{base_name}")

    # 保存处理后的 Markdown 文件
    with open(output_md_path, 'w', encoding='utf-8') as file:
        file.write(converted_md_text)

    print(f"转换完成！文件已保存至: {output_md_path}")


if __name__ == "__main__":
    # 示例调用
    input_md_path = r'D:\Program_Developing\Test_Learn_Program\Python_learnning\Django\pythonProject\Django.md'
    process_markdown_file(input_md_path)